<template>

    <div class="auth_box">
        <el-input disabled :value="valueName"></el-input>
        <!--:default-checked-keys="selectA"  -->
        <el-tree 
            style="margin: 20px 0"
            ref="tree"  
            :data="allPermissions"
            show-checkbox 
            node-key="id"
            default-expand-all
            :props="defaultProps"
            :default-checked-keys="selectA || []" 
        ></el-tree> 
        <el-button :loading="loading" type="primary" @click="save">保存</el-button>
        <el-button @click="router.replace({name: 'role'})">取消</el-button>
        <!-- {{ selectA }} -->
    </div> 
</template>

<script setup lang='ts'>
    import {ref,reactive,nextTick ,onMounted } from 'vue'  
    import {useRoute ,useRouter} from 'vue-router'   
    import { authList,saveAuthId } from '@/api' 
    import { ElMessage } from 'element-plus';
    const tree = ref()
    const route = useRoute()
    const router = useRouter()
    let valueName = ref()
    let loading = ref(false) // 用来标识是否正在保存请求中的标识, 防止重复提交
    let allPermissions = reactive<any>([])
    let selectA = ref<any>([]) 
    const defaultProps = {
        children: 'children',
        label: 'name',
    } 
    // 获取角色名称 
    valueName.value = route.query.name
    // 权限多选列表 选中
    function authListAll(){ 
        authList(route.query.id).then((res) => {
            selected(res.data.children) 
            allPermissions.push(res.data.children[0])  
            // 回显选中状态的节点 
            nextTick(()=>{
                // console.log(tree.value); 
                // console.log(selectA.value.length);  
                tree.value.setCheckedKeys(selectA.value )
            })  
        }).catch((err) => {
            console.log(err); 
        });
    }     
    // Tree递归选中id 
    function selected(arr) {  
        arr.forEach((item) => {  
            // arrAllId.value.push(item.id) 
            if (item.select) { 
                // console.log(item.name,item.select,item.id);
                // 在这里执行相应的操作  
                selectA.value.push(item.id)
            }
            if (item.children) {
                selected(item.children);
            }
        }); 
    }   
    authListAll()   
    // 保存
    function save(){
        let arrSel = ''
        nextTick(()=>{
            loading.value=true
            arrSel = tree.value!.getCheckedKeys().join(",")  
            // console.log(route.query.id);
            saveAuthId(route.query.id,arrSel).then((res) => {
                loading.value=false
                ElMessage.success('保存成功') 
                router.push('/jurisdiction/role')
            }).catch((err) => {
                console.log(err); 
            }); 
        })  
    }
    /*  
    //获取选中状态id
    onMounted(()=>{
        setTimeout(() => {
            console.log(tree.value!.getCheckedKeys())
        }, 1000);
    })   */

</script>

<style lang='less' scoped> 

</style>